<template>
  <div class="home">
    <br>
    <div class="login">
      <div class="content">
        <el-tabs v-model="activeName" class="fixed-tabs" stretch>
          <el-tab-pane label="登录" name="first">
            <el-form v-if="!isEmailLogin" :model="ruleForm" status-icon :rules="rules" ref="ruleForm" class="elpane">
              <el-form-item label="" prop="username" style="font-size: 25px">
                <el-input class="logins" type="text" v-model="ruleForm.username" autocomplete="off"
                          placeholder="账号/手机号"></el-input>
              </el-form-item>
              <el-form-item label="" prop="password">
                <el-input class="logins" type="password" v-model="ruleForm.password" show-password
                          placeholder="请输入密码"/>
              </el-form-item>
              <el-form-item label="" prop="code">
                <el-input style="width: 210px" type="text" v-model="ruleForm.code" autocomplete="on"
                          placeholder="请输入验证码"></el-input>
                <el-button style="background-color: #efefef;margin-left: 10px" @click="getCode" plain>{{
                    code
                  }}
                </el-button>
              </el-form-item>
              <el-form-item label="" style="margin-top: -10px" prop="occupation">
                <el-radio-group v-model="ruleForm.occupation">
                  <el-radio value=0>学生</el-radio>
                  <el-radio value=1>教师</el-radio>
                  <el-radio value=2>管理员</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item style="margin-top: -10px">
                <el-button type="primary" style="width: 150px;margin-top: 10px" round @click="userlogin">登陆</el-button>
              </el-form-item>
              <el-divider style="margin-top: 10px;width: 80%;margin-left: 2%" content-position="center">其他登录方式</el-divider>
              <el-button type="danger" size="default" text @click="isEmailLogin = true">邮箱登陆</el-button>
            </el-form>
            <el-form v-if="isEmailLogin" :model="codeForm" status-icon :rules="rules" ref="codeForm"
                     style="margin-top: 10px"
                     class="elpane">
              <el-form-item label="" prop="email">
                <el-input class="logins" type="email" v-model="codeForm.email" placeholder="请输入邮箱"></el-input>
              </el-form-item>
              <el-form-item label="" prop="code">
                <div class="verify-wrapper">
                  <el-input style="width: 190px;" type="text" maxlength="6" suffix-icon="el-icon-lock"
                            placeholder="请输入验证码" v-model="codeForm.code"/>
                  <el-button class="btn-orange" style="margin-left: 10px" :plain="true" :disabled="disabled"
                             @click="tackBtn">{{ valiBtn }}
                  </el-button>
                </div>
              </el-form-item>
              <el-form-item label="" style="margin-top: -10px" prop="occupation">
                <el-radio-group v-model="codeForm.occupation">
                  <el-radio value=0>学生</el-radio>
                  <el-radio value=1>教师</el-radio>
                  <el-radio value=2>专家</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-button type="primary" round style="width: 150px" @click="codelogin">登陆</el-button>
              <el-divider style="margin-top: 20px;width: 80%;margin-left: 2%" content-position="center">其他登录方式
              </el-divider>
              <el-button type="danger" size="default" text @click="isEmailLogin = false">密码登录</el-button>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="注册" name="second">
            <enrollLogin/>
          </el-tab-pane>
          <el-tab-pane label="重置" name="third">
            <resetLogin/>
          </el-tab-pane>
        </el-tabs>

      </div>
    </div>
  </div>
</template>
<script>
import {emailLoginApi, getLoginCodeApi, loginApi} from "./index.js";
import {useUserStore} from "@/pinia/stores/user";
import {router} from "@/router";
import resetLogin from "@/pages/userLogin/resetLogin.vue";
import enrollLogin from "@/pages/userLogin/enrollLogin.vue";
import axios from "axios";

const userStore = useUserStore()
export default {
  components: {
    resetLogin,
    enrollLogin
  },
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.ruleForm.checkPass !== '') {
          this.$refs.ruleForm.validateField('checkPass');
        }
        callback();
      }
    };
    return {
      ruleForm: {
        password: '',
        username: '',
        occupation: '',
        code: '',
      },
      codeForm: {
        email: '',
        code: '',
        occupation: '',
      },
      isEmailLogin: false,
      activeName: 'first',
      code: '123456',
      disabled: false,
      valiBtn: '获取验证码',
      rules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
        ], code: [
          {required: true, message: '请输入验证码', trigger: 'blur'},
        ],
        password: [
          {validator: validatePass, trigger: 'blur'}
        ],
        occupation: [
          {required: true, message: '请选择角色', trigger: 'change'},
        ],
        email: [
          {required: true, message: '请输入邮箱地址', trigger: 'blur'},
          {type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change']},
          {
            validator: (rule, value, callback) => {
              const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
              if (!emailRegex.test(value)) {
                callback(new Error('请输入正确的邮箱地址'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ]
      }
    };
  },
  mounted() {
    this.getCode();
  },
  methods: {
    userlogin() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          loginApi(this.ruleForm).then(({data}) => {
            userStore.setToken(data.token)
            userStore.setUserInfo(data)
            router.push("/")
          }).catch(roror => {
            this.getCode();
          })
        }
        else {
          this.$message.error('请检查表单信息');
          return;
        }
      });
    },
    getCode() {
      getLoginCodeApi(null).then(({data}) => {
        this.code = data
      }).catch(error => {
        console.log(error)
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    refromnull() {
      this.ruleForm.pass = null
      this.ruleForm.username = null
      router.push("/codeLogin")
    },
    codelogin() {
      this.$refs.codeForm.validate((valid) => {
        if (valid) {
          emailLoginApi(this.codeForm).then(res => {
            console.log(res, "登陆成功")
            if (res.code === 0) {
              //保存用户信息
              userStore.setToken(res.token)
              userStore.setUserInfo(res.data)
              router.push("/")
            }
          }).catch(error => {
            console.log("登陆失败" + error.error)
          })
        } else {
          this.$message("请输入信息")
        }
      });
    },
    tackBtn() {
      //验证码倒数60秒
      // 验证电子邮件地址的正则表达式函数
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (this.codeForm.email === "" || emailRegex.test(this.codeForm.email) === false) {
        this.$message('请输入正确的邮箱');
      } else {
        let time = 60;
        getLoginCodeApi(this.codeForm.email).then(res => {
          if (res.code === 0) {
            console.log("发送成功" + res.data.data)
          } else {
            console.log("发送失败" + res.data.data)
          }
        }).catch(error => {
          console.log("发送失败" + error.error)
        })
        let timer = setInterval(() => {
          if (time === 0) {
            clearInterval(timer);
            this.valiBtn = '获取验证码';
            this.disabled = false;
          } else {
            this.disabled = true;
            this.valiBtn = time + '秒后重试';
            time--;
          }
        }, 1000);
      }
    },
  }
}
</script>

<style scoped>
.home {
  background: url("../userLogin/imag/login.jpg");
  background-size: cover;
  height: 100vh;
}

.el-input {
  font-size: 15px;
}

.el-form-item__error {
  font-size: 16px;
}

.login {
  display: flex;
  width: 400px;
  height: 450px;
  background-color: white;
  opacity: 0.7;
  justify-content: center;
  margin: auto;
  margin-top: 14%;
  text-align: center;

  .logins {
    width: 300px;
    justify-content: center;
  }
}

.zhuce {
  margin-top: 20px;
  z-index: 999;
}

.content {
  display: flex;
  justify-content: center; /* 横向居中 */
  align-items: center; /* 纵向居中 */
  height: 100%; /* 父容器高度占满，便于垂直居中 */
}

.el-tabs {
  width: 100%; /* 保证内容居中不会被压缩 */
}

.elpane {
  display: flex;
  justify-content: center; /* 横向居中 */
  align-items: center; /* 子内容纵向居中 */
  flex-direction: column; /* 子元素内部堆叠方式 */
}

.fixed-tabs {
  position: fixed; /* 固定位置 */
  top: 32%; /* 距离页面顶部 */
  left: 50%; /* 居中 */
  transform: translateX(-50%); /* 修正水平偏移 */
  width: 400px; /* 自定义宽度 */
  z-index: 10; /* 保证标签层级 */
}

.fixed-tabs .el-tabs__nav {
  justify-content: space-between; /* 包括三个标签居中并等距分布 */
}

.el-tabs__item {
  flex: 1; /* 标签均分宽度 */
  text-align: center; /* 居中显示文本 */
}

.el-tabs__nav-wrap {
  display: flex;
  justify-content: center; /* 横向居中 */
}

.el-tabs__nav {
  margin: 0 auto; /* 去除默认间距并居中 */
}

::v-deep .el-tabs__nav-scroll {
  width: 50%;
  margin: 0 auto
}

.text {
  font-size: 14px;
  color: #666;
  white-space: nowrap;
}
</style>
